
import fs from 'fs';
import path from 'path';

class JsonFileManager {
  constructor(filePath) {
    this.filePath = path.resolve(filePath);
  }

  smartPathEscape(originalPath) {
    if (/\\\\/.test(originalPath)) {
      return originalPath;
    }
    // 只对单反斜杠进行转义
    return originalPath.replace(/\\/g, '\\\\');
  }

  read() {
    try {
      const data = fs.readFileSync(this.filePath, 'utf8');
      return JSON.parse(this.smartPathEscape(data));
    } catch (err) {
      if (err.code === 'ENOENT') {
        throw new Error(`文件不存在: ${this.filePath}`);
      }
      throw new Error(`读取JSON文件失败: ${err.message}`);
    }
  }

  write(data) {
    try {
      const jsonStr = JSON.stringify(data, null, 2);
      fs.writeFileSync(this.filePath, jsonStr);
      return true;
    } catch (err) {
      throw new Error(`写入JSON文件失败: ${err.message}`);
    }
  }

  update(updater) {
    try {
      const currentData = this.read();
      const newData = updater(currentData);
      this.write(newData);
      return newData;
    } catch (err) {
      throw new Error(`更新JSON文件失败: ${err.message}`);
    }
  }
}

export { JsonFileManager };

